package com.jmpt.fangbohui.ui;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jmpt.fangbohui.R;
import com.jmpt.fangbohui.bean.LoginBean;
import com.jmpt.fangbohui.bean.OldHouseDetailBean;
import com.jmpt.fangbohui.bean.OldHouseDetailBean.HouseInfoEntity;
import com.jmpt.fangbohui.dao.LoginSQLiteOperator;
import com.jmpt.fangbohui.http.ApiRequest;
import com.jmpt.fangbohui.http.JsonHttpHandler;
import com.jmpt.fangbohui.ui.base.BaseHeadActivity;
import com.jmpt.fangbohui.ui.holder.OldHouseDetailImagesHolder;
import com.jmpt.fangbohui.ui.personalcenter.LoginActivity;
import com.jmpt.fangbohui.utils.ImageLoaderHelper;
import com.jmpt.fangbohui.utils.TimeUtils;
import com.jmpt.fangbohui.utils.ToastHelper;
import com.jmpt.fangbohui.utils.UIUtils;
import com.jmpt.fangbohui.view.MyAlertDialog;
import com.jmpt.fangbohui.view.wheelview.OnWheelChangedListener;
import com.jmpt.fangbohui.view.wheelview.ScreenInfo;
import com.jmpt.fangbohui.view.wheelview.WheelMain;
import com.jmpt.fangbohui.view.wheelview.WheelView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * @包名: com.jmpt.fangbohui.ui
 * @类名: OldHouseDetailActivity
 * @作者: China_Victor
 * @创建时间 : 2015-8-21 上午11:10:28
 * 
 * @描述: 二手房 租房 详情
 */
public class OldHouseDetailActivity extends BaseHeadActivity implements OnWheelChangedListener {
	
	@ViewInject(R.id.fl_detail_images)
	private FrameLayout mFlImagesArea;
	
	@ViewInject(R.id.tv_old_detail_title)
	private TextView mTvTitle;
	
	@ViewInject(R.id.tv_old_detail_address)
	private TextView mTvAddress;
	
	@ViewInject(R.id.ll_old_detail_rentPrice)
	private LinearLayout mLlRentPrice;
	
	@ViewInject(R.id.tv_old_detail_rentPrice)
	private TextView mTvRentPrice;
	
	@ViewInject(R.id.ll_old_detail_salePrice)
	private LinearLayout mLlSalePrice;
	
	@ViewInject(R.id.tv_old_detail_salePrice)
	private TextView mTvSalePrice;
	
	@ViewInject(R.id.tv_old_detail_saleUnitPrice)
	private TextView mTvSaleUnitPrice;
	
	@ViewInject(R.id.tv_old_house_detail_RoomAndHall)
	private TextView mTvRoomAndHall;
	
	@ViewInject(R.id.tv_old_house_detail_area)
	private TextView mTvArea;
	
	@ViewInject(R.id.tv_old_house_detail_floor)
	private TextView mTvFloor;
	
	@ViewInject(R.id.tv_old_house_detail_orientation)
	private TextView mTvOrientation;
	
	@ViewInject(R.id.tv_old_house_detail_decorate)
	private TextView mTvDecorate;
	
	@ViewInject(R.id.tv_old_house_detail_age)
	private TextView mTvAge;
	
	@ViewInject(R.id.iv_old_house_detail_uesr_pic)
	private ImageView mIvUserPic;
	
	@ViewInject(R.id.tv_old_house_detail_user_name)
	private TextView mTvUserName;
	
	@ViewInject(R.id.tv_old_house_detail_user_tel)
	private TextView mTvUserTel;
	//只售
	public static String HOUSE_TYPE_SALE = "1";
	//只租
	public static String HOUSE_TYPE_RENT = "2";
	
	private WheelView yearWheelView;

	private WheelView monthWheelView;

	private WheelView dayWheelView;

	private WheelView hourWheelView;

	private WheelView minWheelView;

	private WheelMain wheelMain;

	private MyAlertDialog dialog;

	protected boolean dialogShow;
	
	
	@OnClick(R.id.tv_old_house_detail_call)
	public void call(View v){
		if(TextUtils.isEmpty(tel)) return;
		Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:" + tel));
        this.startActivity(intent);
	}
	
	private int houseId;
	private String houseName;
	
	public static final String HOUSE_ID = "house_id";
	public static final String HOUSE_TITLE = "house_name";
	
	private OldHouseDetailBean mDetailData;
	private String tel;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initData();
		
		setContentView(R.layout.activity_old_house_detail);
		
		initHeadView();
		
		ViewUtils.inject(this);
		
		loadData();
	}

	private void initData() {
		Intent intent = getIntent();
		if(intent != null){
			houseId = intent.getIntExtra(HOUSE_ID, -1);
			houseName = intent.getStringExtra(HOUSE_TITLE);
		}
	}

	private void initHeadView() {
		// 设置标题
		showTitle(houseName);
		// 设置返回键
		showBackButton(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}
	
	public void refreshUI() {
		//刷新图片显示
		OldHouseDetailImagesHolder imagesHolder = new OldHouseDetailImagesHolder(this);
		imagesHolder.setData(mDetailData.getHouseImg());
		mFlImagesArea.addView(imagesHolder.getRootView());
		
		//基本信息
		List<HouseInfoEntity> houseInfo = mDetailData.getHouseInfo();
		if(houseInfo != null && houseInfo.size() > 0){
			HouseInfoEntity houseInfoEntity = houseInfo.get(0);
			
			mTvTitle.setText(houseInfoEntity.getH_Title());
			mTvAddress.setText(houseInfoEntity.getH_DZ());
			
			mLlRentPrice.setVisibility(HOUSE_TYPE_RENT.equals(houseInfoEntity.getH_SaleOrRent()) ? View.VISIBLE : View.GONE);
			mLlSalePrice.setVisibility(HOUSE_TYPE_SALE.endsWith(houseInfoEntity.getH_SaleOrRent()) ? View.VISIBLE : View.GONE);
			
			mTvRentPrice.setText(houseInfoEntity.getH_RentPrice() + "元/月");
			mTvSalePrice.setText(houseInfoEntity.getH_SalePrice() + "万元/套");
			mTvSaleUnitPrice.setText("(" + houseInfoEntity.getH_SaleUnitPrice() + "元/平)");
			mTvRoomAndHall.setText(houseInfoEntity.getH_Room()+ "室" + houseInfoEntity.getH_Hall() +"厅");
			mTvArea.setText(houseInfoEntity.getH_MJ() + "平方");
			mTvFloor.setText(houseInfoEntity.getH_LC() + "/" + houseInfoEntity.getH_LCTotal() + "层");
			mTvOrientation.setText(houseInfoEntity.getH_CX());
			mTvDecorate.setText(houseInfoEntity.getZXName());
			mTvAge.setText(houseInfoEntity.getH_Age() + "年");
			ImageLoaderHelper.displayImage(houseInfoEntity.getH_picname(), mIvUserPic);
			mTvUserName.setText(houseInfoEntity.getH_SendInfoName());
			tel = houseInfoEntity.getH_SendInfoTel();
			mTvUserTel.setText(tel);
			
		}
		
	}
	
	@OnClick(R.id.btn_appoint)
	public void appoint(View view){
		if(isLogin() != null){
			showDateOptionDialog("选择预约时间");
		}
	}
	
	private void loadData() {
		addRequestHandle(ApiRequest.getOldHouseDetail(houseId, new HttpOldHouseDetailHandler(this)));
	}
	
	class HttpOldHouseDetailHandler extends JsonHttpHandler {

		public HttpOldHouseDetailHandler(Context context, boolean fromCache) {
			super(context, fromCache);
		}

		public HttpOldHouseDetailHandler(Context context) {
			super(context);
		}

		@Override
		public void onStart() {
			setShowProgressDialog("载入数据...");
			setProgressDialogCancleable(false);
			super.onStart();
		}
		
		@Override
		public void onCacheDo(String cache) {
			paseNewHouseDetail(cache);
		}

		@Override
		public void onDo(String response) {
			super.onDo(response);
			paseNewHouseDetail(response);
		}

		public void paseNewHouseDetail(String response) {
			try {
				mDetailData = new Gson().fromJson(response, OldHouseDetailBean.class);
				refreshUI();
			} catch (Exception e) {
				ToastHelper.ShowToast("数据有误,请稍后再试", UIUtils.getContext());
				e.printStackTrace();
			}
		}
	}
	
	/**
     * 选择时间对话框
     */
    private void showDateOptionDialog(String title) {
        LayoutInflater inflater = LayoutInflater.from(this);
        final View timepickerview = inflater.inflate(R.layout.timepicker,
                null);
        yearWheelView = (WheelView) timepickerview.findViewById(R.id.year);
        monthWheelView = (WheelView) timepickerview.findViewById(R.id.month);
        dayWheelView = (WheelView) timepickerview.findViewById(R.id.day);
        hourWheelView = (WheelView) timepickerview.findViewById(R.id.hour);
        minWheelView = (WheelView) timepickerview.findViewById(R.id.min);
        yearWheelView.addChangingListener(this);
        monthWheelView.addChangingListener(this);
        dayWheelView.addChangingListener(this);
        hourWheelView.addChangingListener(this);
        minWheelView.addChangingListener(this);
        minWheelView.setVisibility(View.GONE);
        ScreenInfo screenInfo = new ScreenInfo(this);
        wheelMain = new WheelMain(timepickerview, true);
        wheelMain.screenheight = screenInfo.getHeight();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int h = calendar.get(Calendar.HOUR_OF_DAY);
        wheelMain.initDateTimePicker(year, month, day, h, 0);
        dialog = new MyAlertDialog(this)
                .builder()
                .setTitle(title)
                .setView(timepickerview)
                .setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                    }
                });
        dialog.setPositiveButton("确定", new View.OnClickListener() {
            @Override
			public void onClick(View v) {
				String selectStartTime = wheelMain.getTime() + ":00";
				if (!TimeUtils.timeAvaJudgeMet(TimeUtils.getCurrTime(), selectStartTime, 
						TimeUtils.TIME_TYPE_ALL)) {
					ToastHelper.ShowToast("日期选择不合理", getApplicationContext());
					return;
				}
				try {
					if (TimeUtils.parseToStandardForm(selectStartTime) != null) {
//						tv_startTime.setText(TimeUtils
//								.parseToStandardForm(selectStartTime));
						/** 修改时间后，进行数据刷新 */
						doAppoint(TimeUtils.parseToStandardForm(selectStartTime));
						
					}
				} catch (Exception e) {
					e.printStackTrace();
				}


            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                dialogShow = false;
            }
        });
        try {
            if (TimeUtils.parseToDayOFWeek(System.currentTimeMillis()) != null) {
                dialog.setDay(TimeUtils.parseToDayOFWeek(System.currentTimeMillis()));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        dialog.show();
        dialogShow = true;

    }

	protected void doAppoint(String time) {
		// TODO Auto-generated method stub
		//ToastHelper.ShowToast(time, getApplicationContext());
		LoginBean loginBean = isLogin();
		if(loginBean != null){
			ApiRequest.personAppoint("esyuyue", loginBean, houseId+"", time, new AppointHandler(this));
		}
	}

	public LoginBean isLogin() {
		LoginBean loginBean = new LoginSQLiteOperator(this).query();
		if(loginBean == null){
			//跳转到登录界面
			Intent loginIntent = new Intent(mContext,LoginActivity.class);
			mContext.startActivity(loginIntent);
			return null;
		}
		return loginBean;
	}
	
	class AppointHandler extends JsonHttpHandler {

		public AppointHandler(Context context) {
			super(context);
		}

		@Override
		public void onStart() {
			setShowProgressDialog("正在预约...");
			setProgressDialogCancleable(false);
			super.onStart();
		}

		@Override
		public void onDo(String response) {
			super.onDo(response);
			ToastHelper.ShowToastL("预约成功!稍后会有经纪人与您联系!", getApplicationContext());
		}

	}

	@Override
	public void onChanged(WheelView wheel, int oldValue, int newValue) {
		if (wheelMain != null && dialogShow) {
			if (dialog != null) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(sdf.parse(wheelMain.getTime() + ":00").getTime());
                    if (TimeUtils.parseToDayOFWeek(calendar.getTimeInMillis()) != null) {
                        dialog.setDay(TimeUtils.parseToDayOFWeek(calendar.getTimeInMillis()));
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
		}
	}
	
	
}










